package au.com.carboncycle.gb.engine;

import org.apache.log4j.Logger;

import au.com.carboncycle.gb.engine.Input.Key;
import au.com.carboncycle.gb.engine.graphics.GBRenderer;
import au.com.carboncycle.gb.engine.resources.Art;
import au.com.carboncycle.gb.engine.screen.GameScreen;


public class GBEngine implements Runnable {

	private boolean running = false;
	private Screen screen;
	private Input input = new Input();
	private GBRenderer renderer;
	
	public GBEngine (GBRenderer renderer) {
		this.renderer = renderer;
	}
	
	private static Logger log = Logger.getLogger(GBEngine.class);
	
	@Override
	public void run() {
		running = true;
		
		if (log.isTraceEnabled())
			log.trace("Starting General Brawler Engine");
		
		if (log.isTraceEnabled())
			log.trace("Loading Art");
		
		Art.init();
		
		if (log.isTraceEnabled())
			log.trace("Loaded Art");
		
		
		changeScreen(new GameScreen()); //TODO: move this screen change out of the engine
		
		GameClock clock = new GameClock();
        
		while (running) {
			clock.tick();

            int max = 10;
            while (clock.isUnprocessed()) {
                clock.runDown();
                
               
                screen.tick(input.tick(), clock);

                input.releaseAllKeys();
                
                if (max-- == 0) {
                    clock.endTick();
                    break;
                }
            }
            
            renderer.startRender(screen);
			
            renderer.finishRendering();
		}
	}
	
	void changeScreen (Screen newScreen) {
        if (screen != null) screen.removed();
        screen = newScreen;
        if (screen != null) screen.init(this);
	}
	
	public void appendInput (Key key, boolean down) {
		if (log.isTraceEnabled())
			log.trace(key + ((down) ? " pressed." : " released."));
		
		input.set(key, down);		
		
		if (input.buttons.contains(Key.ESCAPE)) {
			//TODO: show menu - pause
			System.exit(0);
		}
		
	
	}

	

}
